﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Inaction.UI.Extensions.BarExtensions
{
    class BindingEditorExtender
    {
        public static void Extend(BarManager barManager)
        {
            new NextControlStepExtender(barManager);
        }
        public class NextControlStepExtender
        {
            BarManager barManager = null;
            public NextControlStepExtender(BarManager barManager)
            {
                this.barManager = barManager;
                foreach (var item in barManager.FormManager.BindingEditors)
                {
                    foreach (var editor in item.Value)
                    {
                        editor.Value.KeyDown += control_KeyDown;
                    }
                }
            }
            void control_KeyDown(object sender, KeyEventArgs e)
            {
                var editor = sender as BaseEdit;
                if (!editor.Properties.ReadOnly && editor.Enabled
                   && e.KeyData == Keys.Delete && e.Modifiers == Keys.Control)
                {
                    editor.EditValue = null;
                }
                if (barManager.EditMode)
                {
                    if (editor is PopupBaseEdit)
                    {
                        var lue = editor as PopupBaseEdit;
                        if (lue.IsPopupOpen) return;
                    }
                    var editors = barManager.FormManager.BindingEditors[barManager.CurrentBindingInfo.BindingSource];
                    BaseEdit c = null;
                    if (e.KeyCode == Keys.Tab && e.Modifiers == Keys.Shift)
                    {
                        c = editors.Values.OrderByDescending(p => p.TabIndex)
                            .FirstOrDefault(p => p.TabIndex < editor.TabIndex
                            && p.Properties.ReadOnly == false
                            && p.Enabled == true);
                    }
                    if ((e.KeyCode == Keys.Enter || e.KeyCode == Keys.Tab))
                    {
                        c = editors.Values.FirstOrDefault(p => p.TabIndex > editor.TabIndex
                            && p.Properties.ReadOnly == false
                            && p.Enabled == true);
                    }
                    if (c != null)
                    {
                        c.Focus();
                        e.Handled = true;
                        return;
                    }
                }
            }
        }
    }
}
